<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/js/vue.js"></script>
    <script src="../../jquery/jquery.min.js"></script>
    <script src="../../jquery/jquery.form.js"></script>
</head>
<body>
<div id="app">
    <form id="formId">
        <input type="hidden" name="id" v-model="emp.id">
        名称：<input type="text" name="name" v-model="emp.name"><br>
        年龄：<input type="text" name="age" v-model="emp.age"><br>

        <input type="button" id="btn" @click="submitForm" value="提交">
    </form>
</div>
<script>

    function handleResult(data) {
        if(data.code === 0) {
            location.href="index.html";
            return
        }
    }
    function getParams() {
        //获取问号及问号后面的内容
        var url = window.location.search;
        var params = new Object();
        if (url.indexOf("?") != -1) {
            //截取问号后面的内容,再使用&分割多个属性
            var arr = url.substr(1).split("&");
            for (var i = 0; i < arr.length; i++) {
                //使用=分割为keyvalue
                var keyValue = arr[i].split("=");
                params[keyValue[0]] = keyValue[1];
            }
        }
        return params;
    }


    let app = new Vue({
        el: '#app',
        data: {
            emp: {}
        },
        methods: {
            submitForm: function () {
                let param = this.emp;
                if(param.id) {
                    //更新
                    $("#formId").ajaxSubmit({
                        url:'http://localhost:8888/employees/'+param.id,
                        type: 'PUT',
                        success: function (data) {
                            handleResult(data);
                        }
                    })
                    return
                }


                $.post("http://localhost:8888/employees",param,function (data) {
                    handleResult(data);
                    alert(data.msg);
                })
            }
        },
        mounted() {
            let $vue = this;
            let id = getParams().id;
            $.get("http://localhost:8888/employees/"+id,function (data) {
                $vue.emp = data;
            })
        }

    })
</script>
</body>
</html>